package net.mingsoft.zwy.action.web;

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import net.mingsoft.base.entity.ResultData;
import net.mingsoft.basic.dao.IManagerDao;
import net.mingsoft.basic.entity.ManagerEntity;
import net.mingsoft.basic.sao.SM4CloudService;
import net.mingsoft.basic.util.ApplicationContextUtil;
import net.mingsoft.basic.util.SpringUtil;
import net.mingsoft.report_data.action.q.HtmlQuery;
import net.mingsoft.report_data.biz.*;
import net.mingsoft.report_data.entity.ZkDataMessageEntity;
import net.mingsoft.report_data.entity.ZkDataReportConfigEntity;
import net.mingsoft.report_data.enums.ReportPeriodType;
import net.mingsoft.report_data.kafka.avro.ZkReport;
import net.mingsoft.report_data.util.*;
import org.apache.shiro.util.CollectionUtils;
import org.joda.time.DateTime;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author gengfa
 * @date 22/03/05
 */
//@ConditionalOnProperty(value = "ms.mock.enabled")
@RestController
@RequestMapping("/test")
@Slf4j
public class TestController {

    @Resource
    ZkDataBiz dataBiz;

    @Resource
    ZkDataMessageBiz messageBiz;

    @Resource
    ZkDataFocusAreaBiz focusAreaBiz;

    @Resource
    KafkaTemplate<String, ZkReport> kafkaTemplate;

    @Resource
    ZkDataCityPlanningSmartSelection planningSmartSelection;

    @Resource
    FreeMarkerConfigurer configurer;

    @Resource
    IManagerDao iManagerDao;

    @Resource
    SM4CloudService sm4CloudService;

    @GetMapping("init-p")
    public void initp(HttpServletResponse response) throws IOException {
        List<ManagerEntity> entities = iManagerDao.selectAllManagers();
        for (ManagerEntity entity : entities) {
            String encrypt = sm4CloudService.encrypt(entity.getManagerPassword());
            entity.setManagerPassword(encrypt);
            iManagerDao.updateUserPasswordByUserName(entity);
        }
        response.getOutputStream().write("finished".getBytes(StandardCharsets.UTF_8));
    }

    @GetMapping("parse-by-types")
    public void parseMessageByTypes() {
        messageBiz.parseMessage(Collections.singletonList("urn:ga-send:TopHotAreaPerDay"));
    }

    @ApiOperation(value = "生成报告：传指标ID")
    @PostMapping(value = "html", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses(value = {
            @ApiResponse(code = 0, message = "success", response = String.class)
    })
    public void generateHtml(@RequestBody HtmlQuery query, HttpServletResponse response) throws IOException {
        if (CollectionUtils.isEmpty(query.getIds())) {
            return;
        }
        String s = dataBiz.genReport(query);
        response.getOutputStream().write(s.getBytes(StandardCharsets.UTF_8));
    }

    @GetMapping("te")
    public void te(@RequestParam("ids") Long id, HttpServletResponse response) throws IOException {
        HtmlQuery htmlQuery = new HtmlQuery();
        htmlQuery.setIds(Collections.singletonList(id));
        htmlQuery.setAuthor("gof");
        htmlQuery.setTitle("untitled");
        htmlQuery.setPubTime("20220505");
        htmlQuery.setReadCount("1999");
        String s = dataBiz.genReport(htmlQuery);
        response.getOutputStream().write(s.getBytes(StandardCharsets.UTF_8));
    }

    @GetMapping("focus")
    public void focus(HttpServletResponse response) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, IOException {
        HashMap<String, Object> map = new HashMap<>();
/*        focusAreaBiz.getSummary(map);
        focusAreaBiz.getSceneUserTop5(map);
        focusAreaBiz.getTrafficUserTop5(map);
        focusAreaBiz.getOtherAreaUserTop5(map);*/
        focusAreaBiz.getAreaChangingState(map);
        log.info("{}", map);
    }

    @GetMapping("auto-gen")
    public void autoGen(@RequestParam("type") String type,
                        @RequestParam("date") String date,
                        @RequestParam(value = "w", defaultValue = "1") Integer w,
                        HttpServletResponse response) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, IOException {
        /*SMUGGLE_AND_DOCK
        ON_VACATION_FLOW_POPULATION
        FOCUS_AREA
        CITY_PLAN_SMART_SELECT*/
        Object object = ApplicationContextUtil.getObject(type);
        ReportPeriodType reportPeriodType;
        if (w == 1) {
            reportPeriodType = ReportPeriodType.LAST_WEEK;
        } else if (w == 2) {
            reportPeriodType = ReportPeriodType.LAST_MONTH;
        } else if (w == 3) {
            reportPeriodType = ReportPeriodType.LAST_SEASON;
        } else if (w == 4) {
            reportPeriodType = ReportPeriodType.LATTER_HALF_LAST_YEAR;
        } else if (w == 5) {
            reportPeriodType = ReportPeriodType.LAST_YEAR;
        } else {
            reportPeriodType = ReportPeriodType.LAST_WEEK;
        }
        String result = (String) ReportReflectUtil.generate(object, reportPeriodType);
        dataBiz.saveReportManu(date, result, type, ReportPeriodType.getTitlePrefix(reportPeriodType));
        response.getOutputStream().write(result.getBytes(StandardCharsets.UTF_8));
    }


    @GetMapping("register")
    public void register(HttpServletResponse response) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, IOException {
             List<ZkDataReportConfigEntity> reports = dataBiz.getReports();
        dataBiz.autoGenerateReports(ReportPeriodType.LAST_WEEK, reports);
    }

    @GetMapping("property")
    public ResultData getProperty() {
        DateTime now = DateTime.now();
        Map<String, Object> map = new HashMap<>();
        map.put("beginDate", now.minusDays(6).toString("yyyy-MM-dd 00:00:00"));
        map.put("endDate", now.toString("yyyy-MM-dd 00:00:00"));
        /*peoplesLiveHoodBiz.getHotEvents(map);
        peoplesLiveHoodBiz.getPublicOpinionDevelopment(map);
        peoplesLiveHoodBiz.getMediaReportTrending(map);
        peoplesLiveHoodBiz.getPopMediaWithNegativeInfo(map);
        peoplesLiveHoodBiz.getInIslandAntiSmugglerReportCount(map);
        peoplesLiveHoodBiz.getSpecificEmployeeDto(map);*/
        //suspiciousBoatBiz.getHiddenDock(map);

        //zkDataOnVacationFlowPopulationBiz.getUserPeak(map);

        messageBiz.parseMessage();
        return ResultData.build().success(map);
    }

    @GetMapping("send")
    void sendMessage() {
        ZkReport z = new ZkReport();
        z.setMessageId("57");
        z.setUri("urn:ga-send:UserCountByConstantly");
        z.setState("enabled");
        z.setStatusCode(0);
        z.setData("{\"success\": 0}");
        byte[] bytes = AvroUtil.serialize(z);
        kafkaTemplate.send("zk_report", z);
    }

    @GetMapping("parse")
    void parseMessage() {
        messageBiz.parseMessage();
    }

    @GetMapping("export/word")
    void exportWord(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        // 可以设置成 application/vnd.openxmlformats-officedocument.wordprocessingml.document
        response.setContentType(MediaType.MULTIPART_FORM_DATA_VALUE);
        response.setHeader("Content-Disposition", "attachment;fileName=" +
                new String("文档名字.docx".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
        // 源文件：技术报告v3.docx
        FileInputStream originDocxFileStream = new FileInputStream("技术报告v3.docx");
        // 提取的document.xml文件制作成模板document_template.xml
        // Freemarker渲染（文件太长可以改成返回byte[]或InputStream）
        String xmlString = ReportFtlRender.render(configurer, "document_template.xml", new HashMap<>(16));
        // 获取流
        ByteArrayInputStream documentXmlStream = new ByteArrayInputStream(xmlString.getBytes(StandardCharsets.UTF_8));

        // 替换docx中的文件
        ZipUtils.replaceItem(
                ZipUtils.wrapZipInputStream(originDocxFileStream),
                ZipUtils.wrapZipOutputStream(response.getOutputStream()),
                "word/document.xml",
                ZipUtils.wrapZipInputStream(documentXmlStream)
        );

        /*// DOCX解析
        XWPFDocument document = new XWPFDocument(originDocxFileStream);
        // 获取包
        PackagePart packagePart = document.getPackagePart();*/

        //dataBiz.saveReport(response);

        ZkDataMessageEntity o = new ZkDataMessageEntity();
        Optional.of(o).ifPresent(obj -> {
            if (o.getStatusCode() != HttpStatus.OK.value()) {
                // TODO ...
                log.info("todo...");
            }
        });
    }
}
